package com.example.first;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.prefs.PreferenceChangeEvent;

public class RateActivity extends AppCompatActivity implements Runnable{
    private  static final String TAG="Rate";
    float dollarRate=0.13f;
    float euroRate=0.23f;
    float wonRate=123.4f;
    String today="";
    String today1="";
    TextView result;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
        result = (TextView) findViewById(R.id.result);
        Intent intent2 = getIntent();
        dollarRate = intent2.getFloatExtra("dollar_back", 0.13f);
        euroRate = intent2.getFloatExtra("euro_back", 0.24f);
        wonRate = intent2.getFloatExtra("won_back", 123.4f);
        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        dollarRate = sharedPreferences.getFloat("dollar_rate", 0.1f);
        euroRate = sharedPreferences.getFloat("euro_rate", 0.2f);
        wonRate = sharedPreferences.getFloat("won_rate", 123.0f);
        today = sharedPreferences.getString("today", "");
        Log.i(TAG, "OnCreat:get from sp dollarRate" + dollarRate);
        Log.i(TAG, "OnCreat:get from sp euroRate" + euroRate);
        Log.i(TAG, "OnCreat:get from sp wonRate" + wonRate);
        Log.i(TAG, "OnCreat:get from sp today" + today);

        Log.i(TAG, "OnCreat:get from sp dollarRate" + dollarRate);
        Thread t = new Thread(this);
        t.start();
        handler = new Handler(Looper.myLooper()) {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 7) {
                    String str = (String) msg.obj;
                    Log.i(TAG, "handleMessage:str=" + str);
                    result.setText(str);
                }
            }
        };
    }
    public void click(View btn){
        Log.i(TAG, "click: ");
        EditText input=findViewById(R.id.rmb);
        String s =input.getText().toString();
        if(s.length()==0){
            Toast.makeText(this, "请输入数据", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.i(TAG, "click: 进行计算");
        float inp=Float.parseFloat(s);
        float r=0.0f;
        Log.i(TAG,"d"+dollarRate);
        if(btn.getId()==R.id.btn_dollar){
            Log.i(TAG,"d"+dollarRate);
            r=inp*dollarRate;
        }else if(btn.getId()==R.id.btn_euro){
            r=inp*euroRate;
        }else r=inp*wonRate;
        Log.i(TAG, "click: 结果r="+r);
        TextView result= findViewById(R.id.result);
        result.setText(String.valueOf(r));
    }
    public void config(View btn){
        Intent intent=new Intent(this,configActivity.class);
        intent.putExtra("dollar_key",dollarRate);
        intent.putExtra("euro_key",euroRate);
        intent.putExtra("won_key",wonRate);
        startActivityForResult(intent,1);
    }
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 & resultCode == 2) {
            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("key_dollar", 0.1f);
            euroRate = bundle.getFloat("key_euro", 0.1f);
            wonRate = bundle.getFloat("key_won", 0.1f);
            Log.i(TAG, "OnActivityResult:dollarRate=" + dollarRate);
            Log.i(TAG, "OnActivityResult:euroRate=" + euroRate);
            Log.i(TAG, "OnActivityResult:wonRate=" + wonRate);
            SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate", dollarRate);
            editor.putFloat("euro_rate", euroRate);
            editor.putFloat("won_rate", wonRate);
            editor.putString("today",today);
            editor.apply();
            Log.i(TAG,"OnCreativity:save to sp");
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }
    public void run(){
        //时间延时
        Log.i(TAG,"run:run().....");
        try {
            Thread.sleep(3000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        Message msg=handler.obtainMessage(7,"UPDATE");
        handler.sendMessage(msg);
        //获取网络数据
       // URL url=null;
       // try {
        //    url = new URL("https://www.waihui580.com/");
        //    URLConnection http =(HttpURLConnection) url.openConnection();
        //   InputStream in = http.getInputStream();
        //    String html=inputSteam2String(in);
        //    Log.i(TAG,"run:html="+html);
        //} catch(IOException e){
        //    e.printStackTrace();
       // }
        //使用JSOUP获取页面元素
        try{
            Document doc=Jsoup.connect("https://www.waihui580.com/").get();
            Log.i(TAG,"run:title="+doc.title());
        }catch(IOException e){
            e.printStackTrace();
        }
        try{
        String url= "https://www.waihui580.com/";
        Document doc=Jsoup.connect(url).get();
        Log.i(TAG,"run:"+doc.title());
            Elements tables=doc.getElementsByTag("table");
            Element table6=tables.get(0);
            Elements tds=table6.getElementsByTag("td");
            Calendar now = Calendar.getInstance();
            today1=(now.get(Calendar.YEAR)+"年"+(now.get(Calendar.MONTH) + 1)+"月"+now.get(Calendar.DAY_OF_MONTH)+"日");
            if(today.equals(today1)) {
            }
            else{
                for (int i = 0; i < tds.size() - 6; i += 7) {
                    Element td1 = tds.get(i);
                    Element td2 = tds.get(i + 6);
                    String str1 = td1.text();
                    String val = td2.text();
                    Log.i(TAG, "run:" + str1 + "==>" + val);
                    if (str1.equals("美元")) {
                        dollarRate = 100 / Float.parseFloat(val);
                        Log.i(TAG, "dollar=" + dollarRate);
                    }
                    if (str1.equals("欧元")) {
                        euroRate = 100 / Float.parseFloat(val);
                        Log.i(TAG, "euro=" + euroRate);
                    }
                    if (str1.equals("韩国元")) {
                        wonRate = 100 / Float.parseFloat(val);
                        Log.i(TAG, "won=" + wonRate);
                    }
                    //  float v=100f/Float.parseFloat(val);
                }
            }
            Calendar now1 = Calendar.getInstance();
            today=(now1.get(Calendar.YEAR)+"年"+(now1.get(Calendar.MONTH) + 1)+"月"+now1.get(Calendar.DAY_OF_MONTH)+"日");
            Log.i(TAG,"今天是"+today);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private String inputSteam2String(InputStream inputStream) throws IOException {
        final int  bufferSize=1024;
        final char[] buffer=new char[bufferSize];
        final StringBuilder out=new StringBuilder();
        Reader in =new InputStreamReader(inputStream,"UTF-8");
        for(;;){
            int rsz=in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }
}